package se.jocke.nb.proxy.ui.node;

import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.concurrent.CopyOnWriteArraySet;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.TableModel;

/**
 *
 * @author jocke
 */
public class MapTableModel implements TableModel {

    private final Map<String, String> map;

    public static final Entry[] TO_ARRAY_PROTOTYPE = new Entry[]{};

    private final Set<TableModelListener> listeners;

    public MapTableModel() {
        this.map = new TreeMap<String, String>();
        this.listeners = new CopyOnWriteArraySet<TableModelListener>();
    }

    @Override
    public int getRowCount() {
        return map.size();
    }

    @Override
    public int getColumnCount() {
        return 2;
    }

    @Override
    public String getColumnName(int columnIndex) {
        return columnIndex == 0 ? "Name" : "Value";
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return String.class;
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        Entry<String, String>[] toArray = map.entrySet().toArray(TO_ARRAY_PROTOTYPE);
        Entry<String, String> ent = toArray[rowIndex];
        return columnIndex == 0 ? ent.getKey() : ent.getValue();
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        throw new UnsupportedOperationException("Not supported yet.");
    }

    @Override
    public void addTableModelListener(TableModelListener l) {
        listeners.add(l);

    }

    @Override
    public void removeTableModelListener(TableModelListener l) {
        listeners.remove(l);
    }

    public void update(Map<String, String> data) {
        this.map.clear();
        this.map.putAll(data);
        for (TableModelListener listener : listeners) {
            listener.tableChanged(new TableModelEvent(this));
        }
    }

}
